package com.itheima.boottlias.filters;

import cn.hutool.core.util.StrUtil;
import com.itheima.boottlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;

import java.io.IOException;

/**
 * 登录认证过滤器
 * @author ghy
 * @version 1.0
 * @since 2025-07-17 12:04
 */
// @WebFilter("/*")
public class AuthorizedFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("AuthorizedFilter doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1.获取请求URL
        String uri = request.getRequestURI();
        // 2.判断是否为登录
        // 3.是，直接放行
        if(uri.contains("/login")) {
            chain.doFilter(request, response);
            return;
        }
        // 4.不是，获取Token
        String token = request.getHeader("token");
        // 5.非空校验Token
        if(StrUtil.isBlank(token)) {
            // Token不存在
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        // 6.合法校验Token
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Object id = claims.get("id");
            System.out.println(id);
            chain.doFilter(request, response);
        } catch (Exception e) {
            // 非法Token
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }
    }
}
